﻿using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using UIWindows.Commands;
using UIWindows.Tools.Helper;
using UIWindows.UserControls;
using UIWindows.Views.Dialogs;
using UIWindows.GlobalStatics;
using UIWindows.Domains;
using System.Windows.Data;
using UIWindows.Models;
using NewLife.Data;
using NPOI.SS.UserModel;
using System.IO;
using System.Threading;
using XingLucifer.IBase.Enums;
using UIWindows.Enums;
using Kinlo.Entitys;
using System.Windows;
using UIWindows.Services;
using Kinlo.MESDocking;

namespace UIWindows.ViewModels
{
    public class ProductionHistoryViewModel : Domains.ViewModelBase, XingLucifer.IBase.IViewStatus
    {
        #region 分页
        private int _displayDataCount;
        /// <summary>
        /// 当前显示的数量
        /// </summary>
        public int DisplayDataCount
        {
            get { return _displayDataCount; }
            set { SetProperty(ref _displayDataCount, value); }
        }

        private int _quiryTotal;
        /// <summary>
        /// 查询出来的数据
        /// </summary>
        public int QuiryTotal
        {
            get { return _quiryTotal; }
            set { SetProperty(ref _quiryTotal, value); }
        }

        /// <summary>
        /// 当前显示的页数
        /// </summary>
        private int _severalPage;

        public int SeveralPage
        {
            get { return _severalPage; }
            set { SetProperty(ref _severalPage, value); }
        }


        private int _totalPage;
        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPage
        {
            get { return _totalPage; }
            set { SetProperty(ref _totalPage, value); }
        }
        #endregion

        #region 条件
        private bool _isOutput;
        /// <summary>
        /// 是否出站
        /// </summary>
        public bool IsOutput
        {
            get { return _isOutput; }
            set { SetProperty(ref _isOutput, value); }
        }

        public DateTime StartTime { get; set; }
        public string StartValidatingTime { get; set; }
        public DateTime EndTime { get; set; }
        public string EndValidatingTime { get; set; }
        /// <summary>
        /// 条码
        /// </summary>
        public string Barcode { get; set; }
        /// <summary>
        /// 间隔时间
        /// </summary>
        public int Intervals { get; set; } = 100;
        #endregion

        #region 配置显示项
        public GridView ProductionDataView { get; set; }
        #endregion

        #region 单例
        public DisplayItemsStatic _displayItems;
        #endregion
        public AsyncObservableCollection<object> WeightList { get; set; }
        public ProductionHistoryViewModel(DisplayItemsStatic displayItems)
        {
            _displayItems = displayItems;
            WeightList = new AsyncObservableCollection<object>();
            StartTime = DateTime.Now.Date;
            StartValidatingTime = "00:00:00";
            EndTime = DateTime.Now.Date;
            EndValidatingTime = "23:59:59";
            SeveralPage = 1;
            DisplayDataCount = 0;
            TotalPage = 1;
            QuiryTotal = 0;
            ProductionDataView = new GridView();
            Task.Run(() =>
            {
                DateTime time_stat = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 1, 0, 0);
                if (DateTime.Now.Hour < 1) { time_stat = time_stat.AddDays(-1); }
                while (true)
                {
                    if (TimeInterval(time_stat))
                    {
                        ProductionData.Meta.TableName = $"ProductionData_{time_stat:yyyy}{time_stat.GetQuarterly()}";
                        long startTime = SnowflakeManager.GetTimeId(new DateTime(time_stat.Year, time_stat.Month, time_stat.Day, 0, 0, 0, 0, DateTimeKind.Local));
                        DateTime end_Time = StartTime.AddDays(1);
                        long endTime = SnowflakeManager.GetTimeId(new DateTime(end_Time.Year, end_Time.Month, end_Time.Day, 0, 0, 0, 0, DateTimeKind.Local));
                        XCode.Expression expression = ProductionData._.SnowflakeId >= startTime & ProductionData._.SnowflakeId < endTime;
                        if (ExportHelper.Export_ProductionData($".\\TableData\\注液数据{DateTime.Now:yyyy_MM_dd_HH}.xls", expression, _displayItems.WeighingDisplayItems))
                        {
                            "定时导出完成".RunLog(MessageLevelType.信息);
                        }
                        else
                        {
                            "定时导出失败".RunLog(MessageLevelType.信息);
                        }
                        time_stat = time_stat.AddDays(1);
                    }
                    Thread.Sleep(5000);
                }
            });
            //WeightList.Add(new ProductionData { SnowflakeId = 646546464646, BarCode = "sfsdfswerwer", TimeScanCodeBefore = DateTime.Now.GetJSTimeUtc() });
            //WeightList.Add(new ProductionData { SnowflakeId = 646546464646, BarCode = "sfsdfswerwer", TimeScanCodeBefore = DateTime.Now.GetJSTimeUtc() });

        }

        private bool TimeInterval(DateTime dateTime) => ((DateTime.Now.Day - dateTime.Day) == 1) && (DateTime.Now.Hour == 1);

        /// <summary>
        /// 上一页
        /// </summary>
        public DelegateCommand PreviousPage => new DelegateCommand(() =>
        {
            if (SeveralPage - 1 > 0)
            {
                WeightList.Clear();
                SeveralPage -= 1;
                Quiry();
            }
        });

        /// <summary>
        /// 下一页
        /// </summary>
        public DelegateCommand NextPage => new DelegateCommand(() =>
        {
            if ((SeveralPage + 1) <= TotalPage)
            {
                WeightList.Clear();
                SeveralPage += 1;
                Quiry();
            }
        });

        /// <summary>
        /// 数据查询
        /// </summary>
        public DelegateCommand QueryData => new DelegateCommand(() =>
        {
            if (StartTime.Year != EndTime.Year)
            {
                "请选择相同年份".MessageDialogs(MessageLevelType.警告, false, PopUpTypes.Global);
                return;
            }
            if (StartTime.GetQuarterly() != EndTime.GetQuarterly())
            {
                $"请选择季度内查询\r\n1月至3月为一个季度\r\n4月至6月为一个季度\r\n7月至9月为一个季度\r\n10月至12月为一个季度\r\n".MessageDialogs(MessageLevelType.警告, false, PopUpTypes.Global);
                return;
            }
            SeveralPage = 1;
            DisplayDataCount = 0;
            TotalPage = 1;
            QuiryTotal = 0;
            WeightList.Clear();
            _ = DialogHost.Show(new LoadingDialogs(), PopUpTypes.Global.ToString()).ConfigureAwait(false);
            Quiry();
        });

        /// <summary>
        /// 导出数据
        /// </summary>
        public DelegateCommand ExportData => new DelegateCommand(() =>
        {
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
            openFileDialog.Title = "选择文件";
            openFileDialog.Filter = "所有文件(*.*)|*.*";
            openFileDialog.FileName = "选择文件夹";
            openFileDialog.FilterIndex = 1;
            openFileDialog.ValidateNames = false;
            openFileDialog.CheckFileExists = false;
            openFileDialog.CheckPathExists = true;
            openFileDialog.Multiselect = false;//允许同时选择多个文件
            if (openFileDialog.ShowDialog() == true)
            {
                string path = openFileDialog.FileName.Replace("选择文件夹", null, StringComparison.Ordinal);
                _ = DialogHost.Show(new LoadingDialogs(), PopUpTypes.Global.ToString()).ConfigureAwait(false);
                Task.Run(() =>
                {
                    ProductionData.Meta.TableName = $"ProductionData_{StartTime:yyyy}{StartTime.GetQuarterly()}";
                    string[] stime = StartValidatingTime.Split(':');
                    string[] etime = EndValidatingTime.Split(':');
                    long startTime = SnowflakeManager.GetTimeId(new DateTime(StartTime.Year, StartTime.Month, StartTime.Day, int.Parse(stime[0]), int.Parse(stime[1]), int.Parse(stime[2]), 0, DateTimeKind.Local));
                    long endTime = SnowflakeManager.GetTimeId(new DateTime(EndTime.Year, EndTime.Month, EndTime.Day, int.Parse(etime[0]), int.Parse(etime[1]), int.Parse(etime[2]), 999, DateTimeKind.Local));
                    XCode.Expression expression = ProductionData._.SnowflakeId >= startTime & ProductionData._.SnowflakeId <= endTime;
                    if (!string.IsNullOrEmpty(Barcode))
                    {
                        var str_barcode = Barcode.Split("\r\n");
                        XCode.Expression barcode_expression = ProductionData._.BarCode.Contains(str_barcode[0]);
                        for (int i = 1; i < str_barcode.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(str_barcode[i]))
                            {
                                barcode_expression |= ProductionData._.BarCode.Contains(str_barcode[i]);
                            }
                        }
                        expression &= (barcode_expression);
                    }
                    if (ExportHelper.Export_ProductionData($"{path}注液数据{DateTime.Now:yyyy_MM_dd_HH_mm_ss}.xls", expression, _displayItems.WeighingDisplayItems))
                    {
                        "导出完成".MessageDialogs(MessageLevelType.成功, false, PopUpTypes.Global);
                    }
                    else
                    {
                        "导出失败".MessageDialogs(MessageLevelType.错误, false, PopUpTypes.Global);
                    }
                });
            }
        });

        public DelegateCommand<ProductionData> MouseDoubleClick => new DelegateCommand<ProductionData>(sender =>
        {
            if (sender != null) { return; }

        });

        public DelegateCommand<ListView> SelectUpdata => new DelegateCommand<ListView>(async sender =>
        {
            if (sender.SelectedItems.Count == 0)
            {
                return;
            }
            _ = DialogHost.Show(new LoadingDialogs(), PopUpTypes.Global.ToString()).ConfigureAwait(false);

            await Task.Run(() =>
            {
                List<ProductionData> _productions = new List<ProductionData>();
                Application.Current.Dispatcher.Invoke(() =>
                {
                    foreach (var item in sender.SelectedItems)
                    {
                        _productions.Add(item as ProductionData);
                    }
                });

                StringBuilder _msgOutput = new StringBuilder();
                _msgOutput.Append("[出站错误] ");
                bool _isHaveErr = false;
                var _deviceConfigStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.DeviceConfigStatic>();
                var _userConfigStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.UserConfigStatic>();
                var _systemConfig = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.SystemConfigStatic>();
                var _homeStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.HomeStatic>();
                var _parameterStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.ParameterStatic>();
                var _mesParameterStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.MesParameterStatic>();
                var _temporaryStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.TemporaryStatic>();
                Test test = new Test(_deviceConfigStatic, _systemConfig, _userConfigStatic, _parameterStatic, _temporaryStatic, _homeStatic, _mesParameterStatic);

                IMESInteraction _interactionOutput = new ProduceOpenAddInterface(DialogLogHelper.MesLog, DialogLogHelper.MESDialog);
                bool isok = true;
                string ngType = "";
                foreach (var production in _productions)
                {
                    if (production.ResultTotal != ResultTypes.合格)
                    {
                        isok = false;
                        ngType = "不合格";
                    }
                    if (test.BatteryOutboundDataUpload(_interactionOutput, production, isok, ngType) != ResultTypes.合格)
                    {
                        //_isHaveErr = false;
                        _isHaveErr = true;
                        _msgOutput.Append($" {production.BarCode} ");
                    }
                    Thread.Sleep(Intervals);
                }
                if (_isHaveErr)
                {
                    "[出站上传MES]上传完成，但有错误，详情请查看日志!!!".MessageDialogs(MessageLevelType.警告, false, PopUpTypes.Global);
                }
                else
                    "[出站上传MES]上传成功!!!".MessageDialogs(MessageLevelType.成功, false, PopUpTypes.Global);

            });
        });
        public DelegateCommand<ListView> SelectInputAndOutputUpdata => new DelegateCommand<ListView>(async sender =>
      {
          if (sender.SelectedItems.Count == 0)
          {
              return;
          }
          _ = DialogHost.Show(new LoadingDialogs(), PopUpTypes.Global.ToString()).ConfigureAwait(false);

          await Task.Run(() =>
          {
              List<ProductionData> _productions = new List<ProductionData>();
              Application.Current.Dispatcher.Invoke(() =>
              {
                  foreach (var item in sender.SelectedItems)
                  {
                      _productions.Add(item as ProductionData);
                  }
              });

              StringBuilder _msgInput = new StringBuilder();
              _msgInput.Append("[进站错误] ");
              StringBuilder _msgOutput = new StringBuilder();
              _msgOutput.Append("[出站错误] ");
              bool _isHaveErr = false;
              var _deviceConfigStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.DeviceConfigStatic>();
              var _userConfigStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.UserConfigStatic>();
              var _systemConfig = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.SystemConfigStatic>();
              var _homeStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.HomeStatic>();
              var _parameterStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.ParameterStatic>();
              var _mesParameterStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.MesParameterStatic>();
              var _temporaryStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.TemporaryStatic>();
              Test test = new Test(_deviceConfigStatic, _systemConfig, _userConfigStatic, _parameterStatic, _temporaryStatic, _homeStatic, _mesParameterStatic);

              IMESInteraction _interactionInput = new PreventionCheckInterface(DialogLogHelper.MesLog, DialogLogHelper.MESDialog);
              IMESInteraction _interactionWorkOrders = new GetByProductCodeInterface(DialogLogHelper.MesLog, DialogLogHelper.MESDialog);
              IMESInteraction _interactionOutput = new ProduceOpenAddInterface(DialogLogHelper.MesLog, DialogLogHelper.MESDialog);
              foreach (var production in _productions)
              {
                  if (test.BatteryInputDataUpload(_interactionInput, _interactionWorkOrders, production) == ResultTypes.合格)
                  {
                      if (test.BatteryOutboundDataUpload(_interactionOutput, production) != ResultTypes.合格)
                      {
                          _isHaveErr = true;
                          _msgOutput.Append($" {production.BarCode} ");
                      }
                  }
                  else
                  {
                      _isHaveErr = true;
                      _msgInput.Append($" {production.BarCode} ");
                  }
                  Thread.Sleep(Intervals);
              }
              if (_isHaveErr)
              {
                  "[进站+出站上传MES]上传完成，但有错误，详情请查看日志!!!".MessageDialogs(MessageLevelType.警告, false, PopUpTypes.Global);
              }
              else
                  "[进站+出站上传MES]上传成功!!!".MessageDialogs(MessageLevelType.成功, false, PopUpTypes.Global);



          });
      });

        private void Quiry()
        {
            _ = Task.Run(() =>
            {
                try
                {
                    PageParameter page = new PageParameter() { PageSize = 50, PageIndex = SeveralPage };
                    if ((TotalPage == 1 || TotalPage == 0) && string.IsNullOrEmpty(Barcode))
                    {
                        page.RetrieveTotalCount = true;
                    }
                    else
                    {
                        page.TotalCount = QuiryTotal;
                    }
                    ProductionData.Meta.TableName = $"ProductionData_{StartTime:yyyy}{StartTime.GetQuarterly()}";
                    string[] stime = StartValidatingTime.Split(':');
                    string[] etime = EndValidatingTime.Split(':');
                    long startTime = SnowflakeManager.GetTimeId(new DateTime(StartTime.Year, StartTime.Month, StartTime.Day, int.Parse(stime[0]), int.Parse(stime[1]), int.Parse(stime[2]), 0, DateTimeKind.Local));
                    long endTime = SnowflakeManager.GetTimeId(new DateTime(EndTime.Year, EndTime.Month, EndTime.Day, int.Parse(etime[0]), int.Parse(etime[1]), int.Parse(etime[2]), 999, DateTimeKind.Local));
                    XCode.Expression expression = expression = ProductionData._.SnowflakeId >= startTime & ProductionData._.SnowflakeId <= endTime;
                    if (IsOutput)
                        expression &= ProductionData._.ResultOutput != 1;

                    if (!string.IsNullOrEmpty(Barcode))
                    {
                        var str_barcode = Barcode.Split("\r\n");
                        XCode.Expression barcode_expression = ProductionData._.BarCode.Contains(str_barcode[0]);
                        for (int i = 1; i < str_barcode.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(str_barcode[i]))
                            {
                                barcode_expression |= ProductionData._.BarCode.Contains(str_barcode[i]);
                            }
                        }
                        expression &= (barcode_expression);
                    }

                    var list = ProductionData.FindAll(expression, page);
                    foreach (var item in list)
                    {
                        WeightList.Add(item);
                    }
                    if ((TotalPage == 1 || TotalPage == 0) && string.IsNullOrEmpty(Barcode))
                    {
                        TotalPage = (int)page.PageCount;
                    }
                    DisplayDataCount = list.Count();
                    QuiryTotal = (int)page.TotalCount;
                }
                catch (Exception ex)
                {
                    $"历史数据查询异常：{ex}".RunLog(MessageLevelType.警告);
                }
            }).ContinueWith(x =>
            {
                ThreadHelper.CrossThread(sender =>
                {
                    if (DialogHost.IsDialogOpen(PopUpTypes.Global.ToString()))
                    {
                        DialogHost.Close(PopUpTypes.Global.ToString());
                    }
                }, string.Empty);
            }).ConfigureAwait(false);
        }

        public void Load()
        {
            if (!_displayItems.IsDataUpdate)
            {
                return;
            }
            ProductionDataView.Columns.Clear();
            List<DisplayItemsModel> list = new List<DisplayItemsModel>(_displayItems.WeighingDisplayItems);
            list.Sort((x, y) => x.CompareTo(y));
            foreach (var item in list)
            {
                if (item.IsDisplay)
                {
                    var gvc = new GridViewColumn()
                    {
                        DisplayMemberBinding = new Binding()
                        {
                            Path = new System.Windows.PropertyPath(item.Name),
                        },
                        Header = item.Description,
                    };
                    switch (item.DataType)
                    {
                        case "浮点型":
                            gvc.DisplayMemberBinding.StringFormat = "F2";
                            break;
                        case "时间型":
                            gvc.DisplayMemberBinding.StringFormat = "yyyy-MM-dd HH:mm:ss";
                            (gvc.DisplayMemberBinding as Binding).Converter = new Tools.Converter.TimeStampToDateTimeStringConverter();
                            break;
                    }
                    ProductionDataView.Columns.Add(gvc);
                }
            }
            _displayItems.IsDataUpdate = false;
        }

        public void UnLoad()
        {
        }

        void Test1()
        {

            Application.Current.Dispatcher.Invoke(() =>
            {

                StringBuilder _msgOutput = new StringBuilder();
                _msgOutput.Append("[出站错误] ");
                bool _isHaveErr = false;
                var _deviceConfigStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.DeviceConfigStatic>();
                var _userConfigStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.UserConfigStatic>();
                var _systemConfig = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.SystemConfigStatic>();
                var _homeStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.HomeStatic>();
                var _parameterStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.ParameterStatic>();
                var _mesParameterStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.MesParameterStatic>();
                var _temporaryStatic = Domains.ObjectContainer.ResolveSingleton<GlobalStatics.TemporaryStatic>();
                Test test = new Test(_deviceConfigStatic, _systemConfig, _userConfigStatic, _parameterStatic, _temporaryStatic, _homeStatic, _mesParameterStatic);

                IMESInteraction _interactionOutput = new ProduceOpenAddInterface(DialogLogHelper.MesLog, DialogLogHelper.MESDialog);

                ProductionData production = new ProductionData { BarCode = "sfsdf", SnowflakeId = 546465465465 };

                if (test.BatteryOutboundDataUpload(_interactionOutput, production) != ResultTypes.合格)
                {
                    _isHaveErr = true;
                    _msgOutput.Append($" {production.BarCode} ");
                }
                Thread.Sleep(Intervals);

                if (_isHaveErr)
                {
                    "[出站上传MES]上传完成，但有错误，详情请查看日志!!!".MessageDialogs(MessageLevelType.警告, false, PopUpTypes.Global);
                }
                else
                    "[出站上传MES]上传成功!!!".MessageDialogs(MessageLevelType.成功, false, PopUpTypes.Global);
            });

        }
    }

    public class Test : ServierBase
    {
        public Test(DeviceConfigStatic deviceConfig, SystemConfigStatic systemConfig, UserConfigStatic userConfig, ParameterStatic parameterStatic, TemporaryStatic temporaryStatic, HomeStatic homeStatic, MesParameterStatic mesParameterStatic) :
            base(deviceConfig, systemConfig, userConfig, parameterStatic, temporaryStatic, homeStatic, mesParameterStatic)
        {
        }
    }
}
